//
//  StatusesPictureView.swift
//  新浪微博
//
//  Created by mac on 15/12/1.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let pictureCellID = "pictureCellID"
private let pictureCellMargin: CGFloat = 5

class StatusesPictureView: UICollectionView {
    var imageURLs: [NSURL]?{
        didSet{
            if imageURLs != nil{
              testLabel.text = "\(imageURLs!.count)"
            }
            //跟新大小
            let pSize = cacelPictureViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
        }
        
    }
    private func cacelPictureViewSize()->CGSize{
    let imageCount = imageURLs?.count ?? 0
        let maxWidth = screenW - 2.001 * StatusesCellMargin
        let itemWidth = (maxWidth - 2 * pictureCellMargin) / 3
        if imageCount == 0 {
            return CGSizeZero
        }
        if imageCount == 1 {
        //先显示固定大小
            let imageSize = CGSizeMake(180, 120)
            return imageSize
        }
        if imageCount == 4{
        let pW = itemWidth * 2 + pictureCellMargin
            return CGSizeMake(pW, pW)
        }
        //程序走到这里就是多张图的情况了
        //多张图按照3*3九宫格显示
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let size = CGSizeMake(maxWidth, itemWidth * row + pictureCellMargin * (row - 1))
        return size
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor.randomColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
    addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.center)
        }
    }
//懒加载测试label
    private lazy var testLabel: UILabel = UILabel(labeltext: "测试", color: UIColor.redColor(), fontsize: 14)

}
